<?php
/**
 * Description: 获取时政热点
 * User: devforma
 * Date: 16/3/8
 * Time: 11:01
 */

class GetPolitics implements iController {

    const MAX_NUM = 15;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        $isLoggedIn = validateUser($queryArgs) === 1;

        if (empty($queryArgs['count']) || !filter_var($queryArgs['count'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        //限制列表最大数量
        $count = min($queryArgs['count'], self::MAX_NUM);

        $sql = 'SELECT * FROM `data_politics` WHERE 1';

        //如果给定了base_id,则按照base_id进行排序获取数据
        if (!empty($queryArgs['base_id']) && filter_var($queryArgs['base_id'], FILTER_VALIDATE_INT)) {
            $sql .= " AND `id`<={$queryArgs['base_id']}";
        }

        $sql .= " AND `publish_status`='publish' ORDER BY `politic_date` DESC, `id` DESC LIMIT {$count}";

        $data = (array)$cmsdb->getResults($sql);

        //获取用户收藏的时政热点
        if ($isLoggedIn) {
            $ids = array();
            foreach ($data as $row) {
                $ids[] = $row->id;
            }
            $userPolitics = $this->getUserPolitic($queryArgs['user_id'], $ids);
        } else {
            $userPolitics = array();
        }

        //构造返回数据
        $list = array();
        $base = array();
        foreach ($data as $row) {
            if ($row->id == $queryArgs['base_id']) {
                $base = array(
                    'id' => intval($row->id),
                    'title' => trim(html_entity_decode($row->politic_name)),
                    'content' => nl2br(trim(html_entity_decode($row->politic_content))),
                    'date' => $row->politic_date,
                    'is_done' => isset($userPolitics[$row->id]),
                    'is_collected' => isset($userPolitics[$row->id]) && $userPolitics[$row->id]->is_collected,
                    'has_comment' => $row->has_comment
                );
                continue;
            }

            $new = array(
                'id' => intval($row->id),
                'title' => trim(html_entity_decode($row->politic_name)),
                'content' => nl2br(trim(html_entity_decode($row->politic_content))),
                'date' => $row->politic_date,
                'is_done' => isset($userPolitics[$row->id]),
                'is_collected' => isset($userPolitics[$row->id]) && $userPolitics[$row->id]->is_collected
            );

            if ($row->has_comment) {
                $new['comments'] = $this->getPoliticComments($row->id);

            } else {
                $new['comments'] = array();
            }

            $list[] = $new;
        }

        if ($base) {
            if ($base['has_comment']) {
                $base['comments'] = $this->getPoliticComments($base['id']);
            } else {
                $base['comments'] = array();
            }
            unset($base['has_comment']);

            array_unshift($list, $base);
        }

        return genOutput(1, array('list' => $list));
    }

    /**
     * 获取用户看过的时政热点
     *
     * @param $userId
     * @param $politicIds
     * @return array
     */
    private function getUserPolitic($userId, $politicIds) {
        global $cmsdb;

        $string = implode(',', $politicIds);
        $sql = "SELECT `politic_id`, `is_collected` FROM `dl_user_politic` WHERE `user_id`={$userId} AND `politic_id` IN ({$string})";

        $data = $cmsdb->getResults($sql);

        $list = array();
        if (!empty($data)) {
            foreach ($data as $d) {
                $list[$d->politic_id] = $d;
            }
        }

        return $list;
    }

    /**
     * 获取时政热点点评信息
     *
     * @param $politicId
     * @return array
     */
    private function getPoliticComments($politicId) {
        global $cmsdb;

        $data = $cmsdb->getResults('SELECT * FROM `data_politics_comment` WHERE `politic_id`=:pid ORDER BY `id` ASC',
            array(':pid' => $politicId));

        $list = array();
        foreach ($data as $row) {
            $list[] = array(
                'title' => $row->comment_name,
                'comment' => $row->comment_value
            );
        }

        return $list;
    }
}